package com.alex.common.service;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.alex.common.cache.CacheKeys;
import com.alex.common.cache.CommonCacheManager;
import com.alex.common.tools.HostUtils;

@Service
@Deprecated
public class CounterService {

	// 为worker所用
	public int saveCounter(ICounterable counterable, String appName) {
		HashMap<String, Integer> counters = CommonCacheManager.getInstance()
				.get(CacheKeys.Counters, appName);
		int sum = 0;
		if (counters != null && counters.size() > 0) {
			// 集中写库
			sum = counterable.saveCounters(counters);
			// 移除内存
			CommonCacheManager.getInstance()
					.remove(CacheKeys.Counters, appName);
		}
		return sum;
	}

	/**
	 * 
	 * @param counterable
	 * @param appName
	 * @param id
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public void incrCounter(ICounterable counterable, String appName,
			String sid, HttpServletRequest request) throws IOException {
		// e.g. webnote3444134.144.144.21:thetiger
		String clientSign = new StringBuilder(appName).append(sid)
				.append(HostUtils.getClientSign(request)).toString();
		Boolean hasIt = CommonCacheManager.getInstance().get(
				CacheKeys.ClientSigns, clientSign);
		if (hasIt == null || !hasIt) {
			HashMap<String, Integer> counters = CommonCacheManager
					.getInstance().get(CacheKeys.Counters, appName);
			if (counters == null) {
				counters = new HashMap<String, Integer>();
			}

			Integer counter = counters.get(sid);
			if (counter == null) {
				counter = 0;
			}

			// 计数
			synchronized (counter) {
				counters.put(sid, ++counter);
				CommonCacheManager.getInstance().put(CacheKeys.Counters,
						appName, counters);
			}

			// 防重刷
			CommonCacheManager.getInstance().put(CacheKeys.ClientSigns,
					clientSign, true);
		}
	}
}
